import axios from 'axios';

const API_BASE_URL = 'http://mistgc.top:8082';
//普通用户登录
export const login = (username, password) => {
  return axios.post(`${API_BASE_URL}/api/v1/student/login`, {
    username,
    password,
  }).then(response => {
    if (response.data.code === 200) {
      return response.data.data;
    } else {
      throw new Error(response.data.message || '登录失败');
    }
  }).catch(error => {
    console.error('登录请求失败:', error);
    throw error;
  });
};

//管理员登录
export const adminLogin = (username, password) => {
  return axios.post(`${API_BASE_URL}/api/v1/manager/login`, {
    username,
    password,
  }).then(response => {
    if (response.data.code === 200) {
      return response.data.data;
    } else {
      throw new Error(response.data.message || '管理员登录失败');
    }
  }).catch(error => {
    console.error('管理员登录请求失败:', error);
    throw error;
  });
};
//超级管理员登录
export const superAdminLogin = (username, password) => {
  return axios.post(`${API_BASE_URL}/api/v1/admin/login`, {
    username,
    password,
  }).then(response => {
    if (response.data.code === 200) {
      return response.data.data;
    } else {
      throw new Error(response.data.message || '管理员登录失败');
    }
  }).catch(error => {
    console.error('管理员登录请求失败:', error);
    throw error;
  });
};

//首页图书信息
export const fetchBooks = () => {
  return axios.get(`${API_BASE_URL}/api/v1/learning_material/list`);
};

//书本图片
export const fetchCoverImage = (cover_image_id) => {
  return axios.get(`${API_BASE_URL}/api/v1/cover_img/content?id=${cover_image_id}`, {
    responseType: 'blob' // 指定响应类型为 blob
  });
};

//学院信息
export const fetchColleges = () => {
  return axios.get(`${API_BASE_URL}/api/v1/college/list`).then(response => {
    if (response.data.code === 200) {
      return response.data.data;
    } else {
      throw new Error(response.data.message || '获取学院列表失败');
    }
  });
};

//获取学期
export const fetchSemesters = () => {
  return axios.get(`${API_BASE_URL}/api/v1/semester/list`).then(response => {
    if (response.data.code === 200) {
      return response.data.data;
    } else {
      throw new Error(response.data.message || '获取学期列表失败');
    }
  });
};

//班级信息
export const fetchClasses = (grade, collegeId) => {
  return axios.get(`${API_BASE_URL}/api/v1/class/list`, {
    params: { grade, college_id: collegeId }
  }).then(response => {
    if (response.data.code === 200) {
      return response.data.data;
    } else {
      throw new Error(response.data.message || '获取班级列表失败');
    }
  });
};

//学生注册信息创建
export const registerUser = (userData) => {
  return axios.post(`${API_BASE_URL}/api/v1/student/create`, userData, {
    headers: { 'Content-Type': 'application/json' }
  }).then(response => {
    if (response.data.code === 201) {
      return response.data;
    } else {
      throw new Error(response.data.message || '注册失败');
    }
  });
};